import { columns } from '../CheckSheet/components/tableConfig';

<template>
  <div>
    <!-- 查询区域 -->
    <a-card class="card-header">
      <a-form-model ref="modelForm" :model="model" :rules="rules">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="outStoreNum"
              label="出库单号"
            >
              <a-input
                disabled
                placeholder="请输入出库单号"
                v-model.trim="model.outStoreNum"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="pickListNum"
              label="备料单号"
            >
              <a-input
                disabled
                placeholder="请输入备料单号"
                v-model.trim="model.pickListNum"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="worksheetNum"
              label="加工单号"
            >
              <a-input
                disabled
                placeholder="请输入加工单号"
                v-model.trim="model.worksheetNum"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="worksheetQuantity"
              label="加工单数量"
            >
              <a-input-number
                :min="0"
                disabled
                style="width: 100%"
                placeholder="请输入加工单数量"
                v-model.trim="model.worksheetQuantity"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <!-- 表格区域 -->
    <a-card class="card-content">
      <div class="flex flex-a-c flex-j-s-b">
        <div class="requiredNews">计划用料</div>
        <!-- <a-button type="primary" @click="handleWareEdit">编辑</a-button> -->
      </div>
      <br />
      <a-table
        :columns="goodColumns"
        :data-source="tableData"
        :loading="loading"
        :pagination="false"
        :rowKey="(record, index) => record.id"
      >
        <template slot="shelfName" slot-scope="text">
          <div style="text-align:center" v-if="text.length > 0">
            <div v-for="(item, index) in text" :key="index">
              {{ item.shelfName }} 数量:{{ item.quantity }}
            </div>
          </div>
          <div v-else style="color:#c7254e">
            无库存
          </div>
        </template>
      </a-table>
    </a-card>
    <a-card class="card-content">
      <div class="flex flex-a-c flex-j-s-b">
        <div class="requiredNews">出库明细</div>
        <a-button
          type="primary"
          @click="handleWareAdd"
          v-if="receiveMaterialUsername == ''"
          >添加</a-button
        >
      </div>
      <br />
      <a-table
        :columns="wareDesColumns"
        :data-source="model.tmpMaterialPrepareList"
        :loading="loading"
        :pagination="false"
        :rowKey="(record, index) => record.shelfGoodsNumId"
      >
        <template slot="materialPrepareCount" slot-scope="text, record, index">
          <div>
            <a-input-number
              v-if="receiveMaterialUsername == ''"
              style="width:100px"
              v-model="record.materialPrepareCount"
              :min="0"
              :max="
                WareResume == 'WareResume'
                  ? record.nowQuantity
                  : record.quantity
              "
              @change="(e) => quantityChange(e, record, index)"
            />
            <div v-else>
              {{ record.materialPrepareCount }}
            </div>
          </div>
        </template>
        <template slot="action" slot-scope="text, record, index">
          <div>
            <a-popconfirm
              v-if="receiveMaterialUsername == ''"
              okText="确定"
              cancelText="取消"
              title="确定删除吗?"
              @confirm="() => handleDelete(index)"
            >
              <a>删除</a>
            </a-popconfirm>
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 计划数量编辑 -->
    <WareEditModal ref="modalForm" @ok="modalFormOk"></WareEditModal>
    <div class="footer-btn">
      <a-button
        type="primary"
        @click="onSubmit"
        v-if="receiveMaterialUsername == ''"
        >保存</a-button
      >
    </div>
  </div>
</template>

<script>
import {
  goodColumns,
  wareColumns,
  wareDesColumns,
} from "./components/tableConfig";
import api from "@/api/apiServer";
import { tableMinxins } from "@/unit/mixins/tableMinxins.js";
import { beforeRefreshClose } from "@/unit/tool";
import WareEditModal from "./components/WareEditModal.vue";
import WareResume from "./components/WareResume.vue";
export default {
  components: {
    WareEditModal,
    WareResume,
  },
  mixins: [tableMinxins],
  data() {
    return {
      goodColumns,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      // 选中组件参数
      replaceFields: {},
      tableKey: "wareHousePage",
      name: "wareHouseName",
      code: "wareHouseNumber",
      filename: "WarehouseModal",
      columns: wareColumns,
      wareDesColumns,
      tableOption: [],
      receiveMaterialUsername: "",
    };
  },
  computed: {
    rules() {
      return {
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
      };
    },
    WareResume() {
      return this.$route.query.WareResume;
    },
  },
  mounted() {
   
    if (this.$route.query.id) {
      this.getDetail(this.$route.query.id);
    }
    if (this.$route.query.receiveMaterialUsername) {
      this.receiveMaterialUsername = this.$route.query.receiveMaterialUsername;
    }
  },
  methods: {
    // 获取出库单详情
    async getDetail(id) {
      const res = await api.SelPlanMaterial({ id });
      this.model = Object.assign({}, res.data.data);
      delete this.model.warehouseId;
      this.tableData = res.data.data.planMaterialList;
      this.tableData.forEach(async (item) => {
        // 处理后台返回的库位数据
        let shelfName = [];
        shelfName = await this.getSelShelfGoodsNum(item.goodsId);
        this.$set(item, "shelfName", shelfName);
        if (item.needMaterialCount == null) {
          this.$set(item, "needMaterialCount", item.planDemandQuantityNum);
        }
        if (item.totalMaterialPrepareCount == null) {
          this.$set(item, "totalMaterialPrepareCount", 0);
        }
        item.wareNum = 0;
      });
      this.model.tmpMaterialPrepareList = [];
      let quantityM = 0;
      this.tableData.forEach((item) => {
        item.quantityM = quantityM;
      });

      if (this.WareResume == "WareResume") {
        this.$set(this.model, "outStoreNum", this.$route.query.outStoreNum);
        this.getTmpMaterialPrepareRecord();
      } else {
        this.wareDesColumns.forEach((item) => {
          if (item.title === "库位数量") {
            item.key = "quantity";
            item.dataIndex = "quantity";
          }
        });
        this.$forceUpdate();
      }
    },
    async getTmpMaterialPrepareRecord() {
      const res = await api.TmpMaterialPrepareRecord({
        outStoreNum: this.model.outStoreNum,
      });
      this.model.tmpMaterialPrepareList = res.data;
      this.wareDesColumns.forEach((item) => {
        if (item.title === "库位数量") {
          item.key = "nowQuantity";
          item.dataIndex = "nowQuantity";
        }
      });
      this.$forceUpdate();
    },
    // 通过商品获取库位信息接口
    async getSelShelfGoodsNum(goodsId) {
      const res = await api.SelShelfGoodsNum({ goodsId });
      return res.data.map((item) => {
        return {
          shelfName: item.shelfName,
          quantity: item.quantity,
        };
      });
    },
    // 新增商品
    handleWareAdd() {
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.modalEdit(this.model.planMaterialList);
    },
    // 计划用料的编辑
    handleWareEdit() {
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.modalEdit(this.model.planMaterialList);
    },
    quantityChange(val, record, index) {
      if (this.WareResume === "WareResume") {
        if (val > record.nowQuantity) {
          this.$message.error("领料数量超过库位库存数量", 0.5);
        }
      } else {
        if (val > record.quantity) {
          this.$message.error("领料数量超过库位库存数量", 0.5);
        }
      }

      this.$set(
        this.model.tmpMaterialPrepareList[index],
        "materialPrepareCount",
        val
      );
      this.$forceUpdate();
    },
    handleDelete(index) {
      this.model.tmpMaterialPrepareList.splice(index, 1);
      this.$forceUpdate();
    },
    arrDistinctByProp(arr, prop) {
      //只返回第一次出现的，重复出现的过滤掉
      return arr.filter(function(item, index, self) {
        return self.findIndex((el) => el[prop] == item[prop]) === index;
      });
    },
    modalFormOk(tableData) {
      this.model.tmpMaterialPrepareList = [
        ...this.model.tmpMaterialPrepareList,
        ...tableData,
      ];
      this.$set(
        this.model,
        "tmpMaterialPrepareList",
        this.arrDistinctByProp(
          this.model.tmpMaterialPrepareList,
          "shelfGoodsNumId"
        )
      );

      this.model.tmpMaterialPrepareList = this.model.tmpMaterialPrepareList.map(
        (item) => {
          let nowQuantity = null;

          if (item.nowQuantity) {
            nowQuantity = item.nowQuantity;
          } else {
            if (this.WareResume != "WareResume") {
              nowQuantity = null;
            } else {
              nowQuantity = item.quantity;
            }
          }

          return {
            shelfGoodsNumId: item.shelfGoodsNumId,
            materialPrepareCount: item.materialPrepareCount,
            goodsId: item.goodsId,
            goodsCode: item.goodsCode,
            goodsName: item.goodsName,
            quantity: item.quantity,
            shelfName: item.shelfName,
            nowQuantity,
          };
        }
      );
      this.wareDesColumns.forEach((item) => {
        if (item.title === "库位数量") {
          if (this.WareResume === "WareResume") {
            item.key = "nowQuantity";
            item.dataIndex = "nowQuantity";
          } else {
            item.key = "quantity";
            item.dataIndex = "quantity";
          }
        }
      });

      this.$forceUpdate();
    },
    onSubmit() {
      const that = this;
      this.$refs.modelForm.validate((valid) => {
        if (valid) {
          if (that.model.tmpMaterialPrepareList.length > 0) {
            if (that.$route.query.outStoreNum) {
              // 过滤数据 判断当前的数据是否存在领料数量为零的数据
              let newArr = that.model.tmpMaterialPrepareList.filter(
                (item) =>
                  item.materialPrepareCount === 0 || item.nowQuantity === 0
              );
              if (newArr.length > 0) {
                this.$message.error("商品领料数量不能为0");
              } else {
                that.handleEditSubmit();
              }
            } else {
              // 过滤数据 判断当前的数据是否存在领料数量为零的数据
              let newArr = that.model.tmpMaterialPrepareList.filter(
                (item) => item.materialPrepareCount === 0
              );

              if (newArr.length > 0) {
                this.$message.error("商品领料数量不能为0");
              } else {
                that.handleSubmit();
              }
            }
          } else {
            this.$message.error("请添加出库商品");
          }
        } else {
          return false;
        }
      });
    },
    async handleEditSubmit() {
      let tmpMaterialPrepareList = this.model.tmpMaterialPrepareList.map(
        (item) => {
          return {
            id: item.id,
            shelfGoodsNumId: item.shelfGoodsNumId,
            goodsId: item.goodsId,
            goodsName: item.goodsName,
            quantity: item.quantity,
            shelfName: item.shelfName,
            goodsCode: item.goodsCode,
            materialPrepareCount: item.materialPrepareCount,
            materialPrepareNum: this.model.pickListNum,
            outStoreNum: this.model.outStoreNum,
          };
        }
      );
      const res = await api.EditTmpMaterialPrepareRecord({
        tmpMaterialPrepareList,
      });
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        return;
      }
      this.$message.success(res.message);
      this.model = Object.assign({});
      this.$router.go(-1);
    },
    async handleSubmit() {
      if (this.model.warehouseId) {
        let newArr = this.model.warehouseId;
        this.$set(this.model, "warehouseId", Number(newArr.toString()));
      }

      this.model.materialPrepareNum = this.model.pickListNum;
      this.$set(
        this.model,
        "materialPrepareUserId",
        this.$store.state.mes.userInfo.id
      );
      delete this.model.planMaterialList;
      const res = await api.EditMaterialPrepare(this.model);
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        return;
      }
      this.$message.success(res.message);
      this.model = Object.assign({});
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less" scoped>
.card-header {
  margin: 20px 0;
}
button {
  margin-right: 13px;
}
.card-content {
  margin-bottom: 20px;
  .contetnBox {
    border: 1px solid #ebedf0;
    border-radius: 2px;
    padding: 20px 0;
    .headerBox {
      padding: 0 20px;
    }
  }
}
.ant-form-item {
  margin: 10px 0;
}
.tableSpan {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  color: #1a5eff;
}

.footer-btn {
  width: 100%;
  text-align: center;
  margin: 37px 0;
  button {
    width: 200px;
    height: 40px;
    background: #1a5eff;
    border-radius: 2px;
  }
}
.requiredNews {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  color: #1a5eff;
  margin-bottom: 12px;
}
</style>
